package com.ajx.blog.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author: Mr.Li
 * @date: 2022/1/10 14:48
 * @description: 文件上传工具类
 */
public class OnloadUtil {

    //重写文件名称
    public  static  String fileName(String fileName){
        //获取系统当前时间
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        //格式化日期
        String format = dateFormat.format(new Date());

        return  format+fileName;
    }
    //生成文件保存路径
    public  static  String fileRoute(){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy\\MM\\dd");

        return  dateFormat.format(new Date());
    }

    //上传文件的方法
    public  static  String uploadFile(MultipartFile mgUrl) throws IOException {
        //获取文件名称
        String originalFilename = mgUrl.getOriginalFilename();
        //重命名文件
        String s = fileName(originalFilename);
        //生成文件保存路径
        String fileRoute = fileRoute();
        //获取当前路径

        //文件保存路径
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        System.out.println(path);
        String onload = path+"/static/img"+ File.separator+fileRoute;
        System.out.println(onload);
        File file = new File(onload);
        if(!file.exists()){
            file.mkdirs();
        }
        mgUrl.transferTo(new File(onload +File.separator +s));
        return fileRoute+File.separator+s;
    }
}
